package fm.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.controller.BaseController;
import fm.dao.MongoBaseDao;
import fm.dto.AdminUser;
import fm.dto.NeiyiUser;
import fm.entityEnum.CollectTypeEnum;
import fm.exception.BizException;
import fm.exception.TokenInvalidException;
import fm.mongo.MCondition;
import fm.mongo.MRel;
import fm.mongo.MongoTable;
import fm.util.CommonUtils;
import fm.web.CurrentRequest;
import fm.web.MediaTypes;
import fm.yichenet.mongo.service.ExpressService;
import fm.yichenet.mongo.service.GoodMgrService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 文件描述：
 * 更新时间：2017/4/3
 * 更新人： codingmates@gmail.com .
 */
@Controller
@RequestMapping("/goodMgr")
public class GoodMgrController extends BaseController {
    @Autowired
    private GoodMgrService goodMgrService;

    @Autowired
    private fm.mongoService.UserService userService;


    @Autowired
    ExpressService expressService;

    @RequestMapping("/index")
    public String index(ModelMap modelMap) {


        try {
            List<NeiyiUser> users = userService.getAllMerchantUser();
            modelMap.put("shopUsers", users);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/admin/shop/good";
    }

    @ResponseBody
    @RequestMapping(value = "/good/list", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map ajaxGoodDataList(String keyword, Integer status, String shopId, Integer goodTypeId, String sortby,
                                @RequestParam(required = false, defaultValue = "false") Boolean isCount,
                                @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map response = new HashMap();
        DBObject sort = null;
        try {
            Map param = getEmptyParamMap();
            if (StringUtils.isNotEmpty(keyword)) {
                MCondition mc = MCondition.create(MRel.regex).append("goodName", Pattern.compile(keyword));
                param.putAll(mc.toDBObject().toMap());
            }
            if (status != null) {
                param.put("status", status + "");
            }

            if (StringUtils.isNotEmpty(shopId)) {
                param.put("shop_id", shopId);
            }
            else{
                try {
                    if (!isAdmin()) {
                        param.put("shop_id", getCurrentUserId());
                    }
                }
                catch(TokenInvalidException e){
                    LOGGER.error("未登录空默认查全部", e.getMessage());
                }
            }

            if (goodTypeId != null) {
                MCondition mc = MCondition.create(MRel.and).append("good_class_id", goodTypeId.toString());
                param.putAll(mc.toDBObject().toMap());
            }
            if (CommonUtils.isEmpty(sortby)) {
                sortby = "latm";
            }
            sort = new BasicDBObject(sortby, Sort.Direction.DESC.toString());
            if (!isCount) {
                List<DBObject> goods = goodMgrService.getList(param, pageNum, pageSize, sort);
                for (DBObject good : goods) {
                    if (CommonUtils.isEmpty(good.get("good_express"))) {
                        continue;
                    } else {
                        if (good.get("good_express") instanceof String) {
                            String express = (String) good.get("good_express");
                            BasicDBList eps = new BasicDBList();
                            eps.add(express);
                            good.put("good_express", eps);
                            Map updateItem = new HashMap();
                            updateItem.put("good_id", good.get("good_id"));
                            updateItem.put("good_express", eps);
                            goodMgrService.updateGood(updateItem);
                        }
                        BasicDBList list = (BasicDBList) good.get("good_express");
                        String express_text = "";
                        for (int i = 0; i < list.size(); i++) {
                            String expressId = (String) list.get(i);
                            DBObject express = expressService.getExpress(expressId);
                            if (i > 0) {
                                express_text += ",";
                            }
                            express_text += (String) express.get("name");
                        }
                        good.put("express_text", express_text);
                    }
                }

                long count = goodMgrService.countAll(param);
                HashMap data = new HashMap();
                data.put("goods", goods);
                response.put("total", count);
                response.put("data", data);
            } else {
                long count = goodMgrService.countAll(param);
                response.put("data", count);
            }
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }
    @ResponseBody
    @RequestMapping(value = "/good/add", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map addGood(@RequestBody JSONObject good) {
        Map response = new HashMap();
        try {

            NeiyiUser user = getCurrentUser() instanceof AdminUser ? userService.getById((String) good.get("target_shop_id")) : (NeiyiUser) getCurrentUser();
            if (user.getReviewStatus() != 2) {
                throw new BizException("您的认证资料尚未通过审核无法发布商品，请耐心等待，或者联系平台客服了解进度！");
            }
            Map param = getEmptyParamMap();
            param.put("shop_id", user.getId());
            param.putAll(good);
            param.put("good_id", UUID.randomUUID().toString().replaceAll("-", ""));
//            BigDecimal lat = user.getLat();
//            BigDecimal lon = user.getLng();
//            if (lat == null || lon == null) {
//                throw new BizException("您的店铺尚未提交实体店地址经纬度，请先配置店铺地址后再发布商品！");
//            } else {
//                double latd = lat != null ? lat.doubleValue() : 0d;
//                double lngd = lon != null ? lon.doubleValue() : 0d;
//            }
//            param.put("loc", Math.min(latd, lngd) + "," + Math.max(latd, lngd));
            param.put("address", user.getUserAdd().getProvince() + "·" + user.getUserAdd().getCity());
            param.put("status", "1");
            goodMgrService.addGood(param);
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "good/delete", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map deleteGood(@RequestBody JSONObject good) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
            param.putAll(good);
            goodMgrService.delGood(param);
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }

    @ResponseBody
    @RequestMapping(value = "good/update", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map productList(@RequestBody JSONObject good) {
        Map response = new HashMap();
        try {
            Map param = getEmptyParamMap();
            if (CurrentRequest.getCurrentUser() instanceof NeiyiUser) {
                param.put("shop_id", getCurrentUserId());
            }
            param.putAll(good);
            goodMgrService.updateGood(param);
            this.success(response);
        } catch (Exception ex) {
            this.failed(response, ex.getMessage());
            LOGGER.error("请求数据发生错误", ex);
        }
        return response;
    }


    @ResponseBody
    @RequestMapping("/good/info")
    public Map getGoodInfoById(String goodId) {
        Map res = new HashMap();
        try {
            if (StringUtils.isEmpty(goodId)) {
                throw new BizException("参数缺失!");
            }
            Map param = new HashMap();
            param.put("good_id", goodId);
            DBObject good = goodMgrService.getGood(param);
            if (good == null) {
                throw new BizException("未找到相关的商品信息，商品可能已经下架!");
            }
            res.put("data", good);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/good/lists", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map ajaxGoodDataLists(String a) {
        Map response = new HashMap();
        try {
            Map param1 = getEmptyParamMap();

            System.out.println("111111111111111111111111111111111111111111111111");
            param1.put(a, 1);
//            List<DBObject> good = goodMgrService.getList(param1, pageNum1, pageSize1);
//            Collection obj = mongoTemplate.find(query, objClass, collectionName);
            response = param1;
        } catch (Exception a1) {

        }
        ;
        return response;
    }
    @ResponseBody
    @RequestMapping(value = "goodCollect",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public Map collectGood(String good_id,boolean flag){

        Map res = new HashMap();
        try{
            goodMgrService.goodCollect(good_id,flag);
            res.put("data",true);
            this.success(res);
        }catch (BizException ex){
            LOGGER.error("发生错误:",ex);
            this.failed(res,ex.getMessage());
        }
        catch (Exception ex){
            LOGGER.error("发生异常",ex);
            this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
        }
        return res;
    }
}
